package cn.com.hatech.blog.module.admin.dashboard.controller;

import cn.com.hatech.blog.common.constant.ErrorCode;
import cn.com.hatech.blog.common.constant.LogActions;
import cn.com.hatech.blog.common.constant.WebConst;
import cn.com.hatech.blog.common.controller.BaseController;
import cn.com.hatech.blog.common.exception.TipException;
import cn.com.hatech.blog.common.result.RestResponse;
import cn.com.hatech.blog.common.utils.TaleUtils;
import cn.com.hatech.blog.module.admin.dashboard.entity.User;
import cn.com.hatech.blog.module.admin.dashboard.service.ILogService;
import cn.com.hatech.blog.module.admin.dashboard.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @projectName: hatech-blog
 * @package: cn.com.hatech.blog.module.admin.controller
 * @className: AuthController
 * @author: xuruikai
 * @description: 用户后台登录/登出
 * @date: 2020/1/11 14:27
 * @version: 1.0
 */
@Controller
@RequestMapping("/admin")
@Transactional(rollbackFor = TipException.class)
@Slf4j
public class AuthController extends BaseController {

    @Resource
    private IUserService usersService;

    @Resource
    private ILogService logService;

    /**
     * 后台管理登录页面跳转
     *
     * @return
     */
    @GetMapping(value = "/login")
    public String login() {
        return "admin/login";
    }

    /**
     * 管理后台登录
     *
     * @param username
     * @param password
     * @param rememberMe
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "login")
    @ResponseBody
    public RestResponse doLogin(@RequestParam String username, @RequestParam String password, @RequestParam(required = false) String rememberMe,
                                HttpServletRequest request,
                                HttpServletResponse response) {

        Integer errorCount = cache.get("login_error_count");
        try {
            User user = usersService.login(username, password);
            request.getSession().setAttribute(WebConst.LOGIN_SESSION_KEY, user);
            if (!StringUtils.isEmpty(rememberMe)) {
                TaleUtils.setCookie(response, user.getId());
            }
            logService.insertLog(LogActions.LOGIN.getAction(), null, request.getRemoteAddr(), user.getId());
        } catch (Exception e) {
            errorCount = null == errorCount ? 1 : errorCount + 1;
            if (errorCount > ErrorCode.LOGIN_ERROR_MAX_COUNT) {
                return RestResponse.fail("您输入密码已经错误超过3次，请10分钟后尝试");
            }
            cache.set("login_error_count", errorCount, ErrorCode.LOGIN_ERROR_WAIT_TIME);
            String msg = "登录失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                log.error(msg, e);
            }
            return RestResponse.fail(msg);
        }
        return RestResponse.ok();
    }

    /**
     * 注销
     *
     * @param session
     * @param response
     */
    @RequestMapping("/logout")
    public void logout(HttpSession session, HttpServletResponse response, HttpServletRequest request) {
        session.removeAttribute(WebConst.LOGIN_SESSION_KEY);
        Cookie cookie = new Cookie(WebConst.USER_IN_COOKIE, "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        try {
            response.sendRedirect(WebConst.ADMIN_LOGIN_URL);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("注销失败", e);
        }
    }
}
